import java.util.*;
import java.util.regex.Pattern;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class CreateOffer {
	public static void createOffer()throws Exception{
		Connection c = mysqlConnection.connect();
		Scanner in = new Scanner(System.in);
		ResultSet r1 = null;
		ResultSet receiverItemTable = null;
		ResultSet itemTable = null;
		String username = null;
		Pattern p = Pattern.compile("[a-zA-Z]");
		int receiverID = 0;
		boolean value = false;
		while (!value){
			System.out.println("\nEnter the Username of the person you want to trade with");
			username = in.nextLine();
			PreparedStatement findUser = c.prepareStatement("SELECT UserID FROM User WHERE Username = ?");
			findUser.setString(1, username);
			r1 = findUser.executeQuery();
			if(!r1.next()){
				System.out.println("\nUser not found. Try again");
			}
			else{
				receiverID = r1.getInt(1);
				value = true;
			}
		}
		//Outputs a table of items that the user owns
		PreparedStatement ps = c.prepareStatement("SELECT ItemID FROM TradeItem WHERE "+
					"OwnerID =  ?");
		ps.setInt(1, UserLogin.userID);
		itemTable = ps.executeQuery();
		System.out.println("\nItemIDs: ");
		while(itemTable.next()){
			System.out.println(itemTable.getInt(1)+ " ");
		}
		boolean valid2 = false;
		String i = null;
		do{
			System.out.println("\nEnter the item's ItemID you wish to trade");
			i = in.nextLine();
			if(p.matches("[a-zA-Z]", i)){
				System.out.println("\nNo characters allowed");
			}
			else{
				valid2 = true;
			}
		}while(!valid2);
		int userItemID = Integer.parseInt(i);
		//Outputs a table of items that the receiver owns
		PreparedStatement rs = c.prepareStatement("SELECT ItemID FROM TradeItem WHERE "+
				"OwnerID = ?");
		rs.setInt(1, receiverID);
		receiverItemTable = rs.executeQuery();
		System.out.println("\nItemIDs: ");
		while(receiverItemTable.next()){
			System.out.println(receiverItemTable.getInt(1)+ " ");
		}
		
		String j = null;
		boolean valid3 = false;
		do{
			System.out.println("\nEnter the item's ItemID you wish to trade for");
			j = in.next();
			if(p.matches("[a-zA-Z]]", j)){
				System.out.println("\nNo characters allowed");
			}
			else{
				valid3 = true;
			}
		}while(!valid3);
		int tradeItemID = Integer.parseInt(j);
		PreparedStatement ps2 = c.prepareStatement("INSERT INTO Offers " +
				"(OffererID, ReceiverID, ItemID, TradeItemID) VALUES (?, ?, ?,?)");
		
		ps2.setInt(1, UserLogin.userID);
		ps2.setInt(2, receiverID);
		ps2.setInt(3, userItemID);
		ps2.setInt(4, tradeItemID);
		ps2.executeUpdate();
		System.out.println("\nOffer Created");
	}
	public static void main(String []args) throws Exception{
		createOffer();
	}

}
